package com.cloud.configure;

import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * HBase 客户端配置工具
 *
 * @author yzj
 */
@Configuration
public class HBaseConfiguration {

    private static Logger logger = LoggerFactory.getLogger(HBaseConfiguration.class);

    // HBase 服务端地址
    @Value("${hbase.zookeeper.quorums}")
    private String hBaseQuorums;

    // HBase 服务端口
    @Value("${hbase.zookeeper.client-port}")
    private String hBaseClientPort;

    /**
     * 创建HBase数据库连接对象
     *
     * @return
     */
    private Connection getHBaseConn() {
        // 获取HBase链接
        org.apache.hadoop.conf.Configuration conf = org.apache.hadoop.hbase.HBaseConfiguration.create();
        // 指定HBase使用的zk地址
        // 注意:需要在执行HBase Hava代码的机器上配置zk和HBase集群的主机名和ip的映射关系
        conf.set("hbase.zookeeper.quorum", hBaseQuorums);
        conf.set("hbase.zookeeper.property.clientPort", hBaseClientPort);
        // 创建HBase数据库链接
        Connection conn = null;
        try {
            conn = ConnectionFactory.createConnection(conf);
        } catch (IOException e) {
            logger.error("获取HBase链接失败:" + e.getMessage());
        }
        return conn;
    }

    @Bean
    public Admin admin() {
        Admin admin = null;
        try {
            admin = getHBaseConn().getAdmin();
        } catch (IOException e) {
            logger.error("获取HBase/Admin对象失败:" + e.getMessage());
            e.printStackTrace();
        }
        return admin;
    }

}
